import type { Permissions } from '../views/permissions/types.js';
import type { tPermissions } from '../views/permissions/hometypes.js';
export const isJSON = (str: any) => {
  if (typeof str === 'string') {
    try {
      const obj = JSON.parse(str);
      if (typeof obj === 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log('error：' + str + '!!!' + e);
      return false;
    }
  }
};

export function debounce(fn: any, delay: number) {
  let timeoutId: any = null;
  return function (...args: any[]) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

export const formatPrice = (price: number | string) => {
  return (Number(price) / 100).toFixed(2);
};

export function removeEmpty(obj: any): any {
  if (obj === null || obj === undefined || obj === '') return obj;

  if (typeof obj !== 'object') return obj;

  if (Array.isArray(obj)) {
    return obj
      .map(removeEmpty)
      .filter((item) => item !== null && item !== undefined && item !== '');
  }

  return Object.entries(obj)
    .map(([key, value], index) => ({ [key]: removeEmpty(value) }))
    .filter(
      (item) =>
        Object.values(item)[0] !== null && Object.values(item)[0] !== undefined && Object.values(item)[0] !== '',
    )
    .reduce((acc, curr) => ({ ...acc, ...curr }), {});
}

export function removeNull(obj: any): any {
  if (obj === null || obj === undefined) return obj;

  if (typeof obj !== 'object') return obj;

  if (Array.isArray(obj)) {
    return obj
      .map(removeNull)
      .filter((item) => item !== null && item !== undefined);
  }

  return Object.entries(obj)
    .map(([key, value], index) => ({ [key]: removeNull(value) }))
    .filter(
      (item) =>
        Object.values(item)[0] !== null && Object.values(item)[0] !== undefined,
    )
    .reduce((acc, curr) => ({ ...acc, ...curr }), {});
}

export function transformImageUrls(imageUrls: string[]): { uid: string; name: string; status: string; url: string; }[] {
  return imageUrls.map((url, index) => {
      const name = url.split('/').pop()?.split('?')[0] || ''; // 提取文件名，并去除可能的查询参数
      return {
          uid: (index + 1).toString(),
          name: name,
          status: 'done',
          url: url
      };
  });
}

/**
 * 转换树形数据结构，将 name 字段转换为 title，id 字段转换为 key
 * @param {Array} nodes - 原始树形数据结构
 * @returns {Array} - 转换后的树形数据结构
 */

export function transformPermissionsTreeData(nodes: Permissions[]): tPermissions[] {
  console.log(nodes);
  return nodes.map(node => {
    console.log(node);
    const transformedNode = {
      title: node.name,
      key: node.id,
      level:node.level,
  icon:node.icon,
  module:node.module,
  component:node.component,
  redirect:node.redirect,
  type:node.type,
  hidden:node.hidden,
  weight:node.weight,
  creator:node.creator,
  created_at:node.created_at,
  updated_at:node.updated_at,
  deleted_at:node.deleted_at,
  keepalive:node.keepalive,
  path:node.path,
  parent_id:node.parent_id,
  meta:node.meta,
  groups:node.groups, 
  children: node.children 
    };

    console.log(transformedNode);
    if (node.children && node.children.length > 0) {
      transformedNode.children = transformPermissionsTreeData(node.children);
    }

    return transformedNode;
  });
}

// 二维数组中筛选出符合条件的对象，并提取目标键的值
export function filterAndExtract<T extends Record<string, any>, K extends keyof T, TargetKey extends keyof T>(
  data: T[][], // 使用 T[][] 替代 Array<Array<T>>，更简洁且类型兼容性更强
  filterKey: K,
  filterValue: T[K],
  targetKey: TargetKey
): T[TargetKey][] {
  return data.flatMap(subArray =>
    subArray
      .filter(item => item[filterKey] === filterValue)
      .map(item => item[targetKey])
      .filter((value): value is T[TargetKey] => value !== undefined)
  );
}

// 客户端ID生成器（带本地存储）
export function generateClientId() : string {
  const STORAGE_KEY = 'client_id'
  
  // 尝试从本地存储获取
  const storedId = localStorage.getItem(STORAGE_KEY)
  if (storedId) return storedId

  // 生成新的UUID v4
  const newId = crypto.randomUUID()
  localStorage.setItem(STORAGE_KEY, newId)
  return newId
}

// 获取域名
export function getDomainName(url?:string) : string {
  const urlString = url ? url : import.meta.env.VITE_GLOB_API_URL ;
  
  // 从urlString中提取域名
  const urlObj = new URL(urlString);  
  const hostname = urlObj.hostname; // 获取域名部分
  
  return hostname
}


/*
export const showSelectedObjectKeys = (
  originalObject: object,
  keysToShow: string[]
): object => {
  const filteredObject = {};
  Object.keys(originalObject).forEach((key) => {
    if (keysToShow.includes(key)) filteredObject[key] = originalObject[key];
  });
  return filteredObject;
};

export const hideObjectKeysWithoutValues = (
  originalObject: object
): object => {
  const filteredObject = {};
  Object.keys(originalObject).forEach((key) => {
    if (originalObject[key] !== undefined) filteredObject[key] = originalObject[key];
  });
  return filteredObject;
};

export const hideSelectedObjectKeys = (
  originalObject: object,
  keysToHide: string[]
): object => {
  const filteredObject = {};
  Object.keys(originalObject).forEach((key) => {
    if (!keysToHide.includes(key)) filteredObject[key] = originalObject[key];
  });
  return filteredObject;
};
*/
